# coding:utf-8
import wx
import shutil
from common.iniconfig import iniconfig
from mainFrame import mainFrame
from modules.baidu.baidu import d_baidu
from modules.common import delete_file_folder
from dict_option import dict_option
from common.version import program_name,program_version
import os
import gettext
import lang
import webbrowser
from history import dict_history
from modules.common import getsource
from common.dy_import.dy_import import Dynload

class dict_Frame(mainFrame):
        def __init__( self, parent ):
                mainFrame.__init__(self,parent)
                self.m_bcomboBox1.Bind( wx.EVT_TEXT_ENTER, self.OnSearchTestEnter )
		self.m_bcomboBox1.Bind( wx.EVT_KEY_DOWN, self.OnComboBoxKeyDown )
                self.m_bpSearch.Bind(wx.EVT_BUTTON,self.OnSearchTestEnter)
		self.m_bpRead.Bind(wx.EVT_BUTTON,self.OnRead)
                self.Bind( wx.EVT_MENU, self.OnOption, id = self.m_menuItem1.GetId() )
                self.Bind( wx.EVT_MENU, self.OnQuit, id = self.m_menuItem2.GetId() )
		self.Bind( wx.EVT_MENU, self.OnAbout, id = self.m_menuItem10.GetId() )
		self.m_listBox1.Bind( wx.EVT_KEY_DOWN, self.OnKeyDown )
		self.m_bcomboBox1.Bind( wx.EVT_TEXT, self.OnText )
		for i in self.menu_dict:
			self.Bind( wx.EVT_MENU, self.OnMenuUse, id=self.menu_dict[i][1].GetId())
			self.Bind( wx.EVT_MENU, self.OnMenuOption, id = self.menu_dict[i][2].GetId())
			self.Bind( wx.EVT_MENU, self.OnMenuAbout, id = self.menu_dict[i][3].GetId() )
		
		self.m_bcomboBox1.Bind( wx.EVT_COMBOBOX, self.OnSearchTestEnter )
		self.m_listBox1.Bind( wx.EVT_LISTBOX_DCLICK, self.OnListBoxDClick )
		self.Bind( wx.EVT_MENU, self.OnClearHistory, id = self.m_menuItem8.GetId())
		self.m_html.Bind( wx.html.EVT_HTML_CELL_HOVER, self.OnHtmlCellHover )
		self.Bind( wx.EVT_CLOSE, self.OnCloseFrame )
		self.m_html.Bind( wx.html.EVT_HTML_LINK_CLICKED, self.OnLinkClicked )		
		self.m_statusBar1.SetStatusText("%s  %s"%(program_name(),program_version()),2)
		self.ini=iniconfig("settings")
		icon=wx.EmptyIcon()
		icon.LoadFile(u"gui/image/book_ex.ico",wx.BITMAP_TYPE_ICO) 
		self.SetIcon(icon)
		
		self.history=dict_history(os.getcwd()+"/history")
		self.m_bcomboBox1.Clear()
		for m in self.history.read_history():
			self.m_bcomboBox1.Append(m,wx.Bitmap( u"gui/image/baidu_ex.jpg", wx.BITMAP_TYPE_ANY ))	
		self.m_bcomboBox1.SetFocus()
		#self.m_listBox1.Clear()
		#self.m_listBox1.AppendItems(self.dict_list)
		
		
		
        def __del__(self):
                pass
	
	def OnComboBoxKeyDown( self, event ):
		if event.GetKeyCode()==wx.WXK_DOWN:
			self.m_listBox1.SetSelection(0)
			self.m_listBox1.SetFocus()
		else:
			event.Skip()		
			
	def OnText( self, event ):
		c=self.m_bcomboBox1.GetValue().strip()
		if c=="":
			self.m_listBox1.Clear()
			return
		self.m_listBox1.Clear()
		a=[]
		for i in self.dict_list:
			if i.startswith(c):
				self.m_listBox1.Append(i)

		
        def OnCloseFrame( self, event ):
		self.Destroy()
	
	def OnKeyDown(self,event):
		if event.GetKeyCode()==wx.WXK_RETURN :
			#a=self.m_bcomboBox1.GetValue()
			#b=self.m_listBox1.GetSelection()
			self.m_bcomboBox1.SetText(self.m_listBox1.GetString(self.m_listBox1.GetSelection()))
			self.OnSearchTestEnter(None)
			#self.m_bcomboBox1.SetValue(a)
			#self.m_listBox1.SetSelection(b)
			self.m_listBox1.SetFocus()		
		else:
			event.Skip()
			
	def OnListBoxDClick( self, event ):
		#a=self.m_bcomboBox1.GetValue()
		#b=self.m_listBox1.GetSelection()
		self.m_bcomboBox1.SetText(self.m_listBox1.GetString(self.m_listBox1.GetSelection()))
		self.OnSearchTestEnter(None)
		#self.m_bcomboBox1.SetValue(a)
		#self.m_listBox1.SetSelection(b)
		self.m_listBox1.SetFocus()
		
        def OnRead(self,event):
		b=self.m_bcomboBox1.GetValue().strip()
		if b=="":
			return
		temp=Dynload("modules.%s.%s" % (self.cr,self.cr),['.'])
		temp2=temp.getClassInstance("d_"+self.cr)
		temp.execMethod(temp2,"getmp3",self.m_bcomboBox1.GetValue().strip(),self)
		del temp,temp2	
		

        def OnSearchTestEnter(self,event):
                b=self.m_bcomboBox1.GetValue().strip()
		self.m_statusBar1.SetStatusText(b,1)
		self.history.add_history(b)
		self.m_bcomboBox1.Append(b,wx.Bitmap( u"gui/image/baidu_ex.jpg", wx.BITMAP_TYPE_ANY ))	

                if b == "":
                        self.OnAbout(None)
                else:
			try:
			        temp=Dynload("modules.%s.%s" % (self.cr,self.cr),['.'])
		                temp2=temp.getClassInstance("d_"+self.cr)
		                self.m_html.SetPage(temp.execMethod(temp2,"getcontentHTML",b))
		                del temp,temp2
			except UnboundLocalError,e:
				self.m_html.SetPage("<font color=Red><h1>%s</h1></font><p>%s</p>" % (_("You are offline!"),e.strerror))				
			except IOError,e:
				self.m_html.SetPage("<font color=Red><h1>%s</h1></font><p>%s</p>" % (_("You are offline!"),e.strerror))
	                except UnicodeError,e:
				self.m_html.SetPage("<font color=Red><h1>%s</h1></font>" % _("Please choose the appropriate dictionary!"))
	                except Exception,e:
				pass
	        if self.ini.get_item("auto_read")=="True":
			self.OnRead(None)
	
	def OnOption( self, event ):
		a=dict_option(self)
		a.ShowModal()
		
	def OnQuit( self, event ):
		self.Close()	
	
	def OnAbout( self, event ):
		self.m_html.SetPage('''<html><title>%s</title><font color=Red size=100><h1>%s</h1></font><img src = "gui/image/book_ex2.jpg" alt="dict_pic"><h4>%s</h4>
		<br><p>%s</p><p>%s</p><p>%s<a href="mailto:hzh0512@gmail.com">%s</a></p><font size=6><p>hzh</p></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src = "gui/image/wxPython.png" alt="wxPython Pic">
		</html>
		'''	% (_("About ")+program_name(),program_name()+ " "+program_version(),_("GUI written in wxPython,others in Python."),
		               _("This program is for easier looking up , the functions are still to be profected .<br>Thanks for using  <font color=Red size=14>")+program_name()+_("</font>.<br> Have fun!:)")
		               ,_("You can add language modules, which are in the directory 'locale',<br> or you can even add regex modules for other sites ,which are in directory 'modules'")
		               ,_("You can mail me at  "),_("hzh0512@gmail.com")))
		
	
	def OnLinkClicked( self, event ):
		a=self.cr
		temp=str(event.GetLinkInfo().GetHref())
		if temp.startswith('''http://baike.baidu.com/view'''):
			webbrowser.open(temp)
		elif temp.startswith('''/s?wd='''):
			self.cr="baidu"
			self.m_bcomboBox1.SetValue(temp[6:].replace("+"," "))
			self.OnSearchTestEnter(None)
			self.cr=a
	
	
	def OnClearHistory (self,event):
		self.history.del_history()
		self.m_bcomboBox1.Clear()
	
	def OnMenuAbout(self,event):
		for i in self.menu_dict:
			if self.menu_dict[i][3].GetId()==event.GetId():
				temp=Dynload("modules.%s.%s" % (self.menu_dict[i][0],self.menu_dict[i][0]),['.'])
				temp2=temp.getClassInstance("d_"+self.menu_dict[i][0])
				self.m_html.SetPage(temp.execMethod(temp2,"__str__"))	
				del temp,temp2
				return		
		
	def OnMenuOption(self,event):
		for i in self.menu_dict:
			if self.menu_dict[i][2].GetId()==event.GetId():
				temp=Dynload("modules.%s.%s" % (self.menu_dict[i][0],self.menu_dict[i][0]),['.'])
				temp2=temp.getClassInstance("d_"+self.menu_dict[i][0])
				temp.execMethod(temp2,"setoptiongui",self)
				del temp,temp2
				return
	
	def OnMenuUse(self,event):
		for i in self.menu_dict:
			if self.menu_dict[i][1].GetId()==event.GetId():
				if self.menu_dict[i][1].IsChecked():
					
					self.cr=self.menu_dict[i][0]
					temp=Dynload("modules.%s.%s" % (self.cr,self.cr),['.'])
					temp2=temp.getClassInstance("d_"+self.cr)
					self.dict_list=temp.execMethod(temp2,"getwordlist")	
					self.m_listBox1.Clear()
					self.m_staticText3.SetLabel(self.crs[self.cr])
					self.menu_dict[i][2].Enable(True)
					if self.m_bcomboBox1.GetValue().strip()!="" :
						self.OnText(None)
					for k in self.menu_dict:
						if self.menu_dict[k][0]!=self.cr:
							self.menu_dict[k][2].Enable(False)
							self.menu_dict[k][1].Check(False)
				else:
					self.menu_dict[i][1].Check(True)
					wx.MessageBox(_("You can not cancel the current dictionary!"),_("Error"),wx.OK | wx.ICON_INFORMATION,self)
				
				return
	
	def OnHtmlCellHover( self, event ):
		if event.GetCell().GetLink()==None:
			self.m_statusBar1.SetStatusText("",0)
		else:
			temp=event.GetCell().GetLink().GetHref()
			if temp.startswith('''http://baike.baidu.com/view'''):
				self.m_statusBar1.SetStatusText(_("Baike : ")+temp,0)	
			elif temp.startswith('''/s?wd='''):		
				self.m_statusBar1.SetStatusText(_("Look up word : ")+temp[6:].replace("+"," "),0)
